package com.hqu.environment.controller.image;

import com.hqu.environment.annotation.IgnoreAuth;
import com.hqu.environment.constant.Constant;
import com.hqu.environment.utils.Result;
import com.hqu.environment.utils.Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Description: 图片访问
 * @Date: 2019/04/23 17:14
 * @Author: 邓勇嘉
 **/
@Controller
public class ImageController {
    private final static String IMAGE_URL= Constant.DEST;

    @IgnoreAuth
    @RequestMapping(value = "/image/{image:.+}", method = RequestMethod.GET)
    @ResponseBody
    public void image(HttpServletResponse response, @PathVariable("image") String image) throws IOException {
        try{
            File file = new File(IMAGE_URL + image);
            InputStream input = new FileInputStream(file);
            byte[] bs = new byte[1024];
            int len;

            OutputStream output = response.getOutputStream();
            // 读取到的数据长度
            while ((len = input.read(bs)) != -1) {
                output.write(bs, 0, len);
                output.flush();
            }
            input.close();
            output.close();
        }catch (Exception e){

        }
    }

    @IgnoreAuth
    @RequestMapping(value = "/uploadImage")
    @ResponseBody
    public Result uploadImage(MultipartFile file) {
        String filename = Util.uploadFile(file);
        return Result.success().add("fileName",filename);
    }
}
